package com.jike.shop.cloud.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Component
@Slf4j
public class RedisLock {
    private final StringRedisTemplate redisTemplate;
    private static final String LOCK_VALUE = "1";
    private static final Integer DEFAULT_EXPIRE_TIME = 1000;

    public boolean lock(@NonNull String key) {
        return lock(key, DEFAULT_EXPIRE_TIME);
    }

    public boolean lock(@NonNull String key, @NonNull int expireTime) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, LOCK_VALUE, expireTime, TimeUnit.MILLISECONDS);
        if (result == null) {
            log.info("lock key = {} fail", key);
            return false;
        }
        log.info("lock key = {},expireTime = {}ms, result = {}", key, expireTime, result);
        return result;
    }

    public boolean releaseLock(@NonNull String key) {
        Boolean delete = redisTemplate.delete(key);
        if (delete == null) {
            log.info("release lock key = {} fail", key);
            return false;
        }
        log.info("release lock key = {} success", key);
        return delete;
    }
}
